<?php

namespace app\api\controller;

use app\admin\model\AuthDepartment;
use app\common\controller\Api;
use EasyWeChat\Factory;
use app\admin\model\Admin;
use think\App;
use workflow\workflow;


/**
 * 数据接口
 */
class Data extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
	/**
     * 公共
	 * @author gzy
	 * @date   2018年8月12日 10:15:00
     */
	public function _initialize(){
        parent::_initialize();
		//获取默认值
	}

    public function Agent()
    {
        $config = [
            'corp_id'=>'wxa8333bbf9962d0e0',
            'agent_id'=>'1000025',
            'secret'   =>'49BinJYmJglgFqs7FtNSNmvS1t8sa9Qy7IxsoiNZsDs',//小助手key
            'token'=>'KsJxHcXNx4GGnVEHXn0',
            'aes_key'=>'7PBI4KTGyMpQ8dLQyf4ojzj22jznFjuRP66qxlsl2Ot',
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',//debug  info  notice  warning  error  critical  critical  alert  emergency
                'file' => __DIR__.'/log/WechatAgent.log',
            ],
        ];
        $app = Factory::work($config);
        $app->server->push(function ($message) {
            if($message['Event'] =='taskcard_click')
            {
                return '发送任务的按钮'.$message['EventKey'].'任务TaskId'.$message['TaskId'];
            }
            return '';
            return json_encode($message);
        });
        $response = $app->server->serve();
        $response->send();exit;
    }
    public function Plan()
    {
        $config = [
            'corp_id'=>'wxa8333bbf9962d0e0',
            'agent_id'=>'1000017',
            'secret'   =>'wcGnDj5lA6exfEy6tHEfXciXpwT5RIi2tQThMwcKOMw',//小助手key
            'token'=>'7TagHG9RgV7',
            'aes_key'=>'ITXg98tKmV4TtGHNnDLRQs9HbKVGFNaNS1blUlAgKLd',
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',//debug  info  notice  warning  error  critical  critical  alert  emergency
                'file' => __DIR__.'/log/WechatPlan.log',
            ],
        ];
        $app = Factory::work($config);
        $app->server->push(function ($message) {
            if($message['Event'] =='taskcard_click')
            {
                return '发送任务的按钮'.$message['EventKey'].'任务TaskId'.$message['TaskId'];
            }
            return '';
            return json_encode($message);
        });
        $response = $app->server->serve();
        $response->send();exit;
	}
    /**
     * 部门操作 wechat端
     * @author gzy
     * @date   2018年8月13日 09:10:21
     */
    public function dept() {
		if ($this->request->isPost()) {
			$data = $this->request->post();
			$action = $data['action'];
			unset($data['action']);
			//判断模块是否存在
			if(!in_array($action, array('add','edit','delete','multi'))) return  $this->error(GetErrorLang('-1'));
			//获取默认参数 user
			$DeptConfig = $this->getConfig($this->getDefault('Dept'));
			//初始化
			$app = Factory::work($DeptConfig);
			//创建部门 //编辑编辑
			if('add' === $action || 'edit' === $action){
				if(!$data['pid']) return $this->error(GetErrorLang('-2'));
				$info = [];
				$info['parentid'] = $data['pid'];
				$info['name'] = $data['name'];
				if('edit' === $action){
					$id = $data['id'];
					unset($data['id']);
				}
				if('add' === $action){
					$result = $app->department->create($info);
				}elseif('edit' === $action){
					$result = $app->department->update($id,$info);
					if($result['errcode'] == '60003') {
						$info['id'] = $id;
						$result = $app->department->create($info);
					}
				}
			}elseif('multi' === $action){
				$result = $app->department->list();
			}elseif('delete' === $action){
				$result = $app->department->delete($data['id']);
			}
			//返回
			if($result['errcode'] !== 0) return $this->error(GetErrorLang($result['errcode']),$result);
			return $this->success('成功',$result);
			
		}
		return  $this->error(GetErrorLang('-1'));
    }
	/**
     * 成员操作 wechat端
	 * @author gzy
     * @date   2018年8月12日 15:15:00
     */
    public function user() {
		if ($this->request->isPost()) {
	
			$data = $this->request->post();
			$action = $data['action'] ;
			unset($data['password']);
			unset($data['action']);
			//判断模块是否存在
			if(!in_array($action, array('add','edit','delete','multi'))) return  $this->error(GetErrorLang('-1'));
			//获取默认参数 user
			$UserConfig = $this->getConfig($this->getDefault('User'));
			//初始化
			$app = Factory::work($UserConfig);
			//创建成员 //编辑成员	
			if('add' === $action || 'edit' === $action){
				if('edit' === $action){
					$userid = $data['userid'];
					unset($data['userid']);
				}
				//上传头像
				if(!empty($data['avatar_url']) && !strpos($data['avatar_url'],'p.qlogo.cn')){
					define('IMG_URL_DIR',substr(dirname(__FILE__),0,-27).'/public'.DIRECTORY_SEPARATOR);
					//没用
					//$img_info = $app->media->uploadImage(request()->domain().$data['avatar_url']);
					$img_info = $app->media->uploadImage(IMG_URL_DIR.$data['avatar_url']);
					if($img_info['errmsg'] == 'ok') $data['avatar_mediaid'] = $img_info['media_id'];
				}
				
				unset($data['avatar_url']);
				if('add' === $action){
					$result = $app->user->create($data);
				}elseif('edit' === $action){
					$result = $app->user->update($userid,$data);
				}
				$result['avatar_mediaid'] = '';
				$result['avatar_mediaid'] = !empty($data['avatar_mediaid']) ? $data['avatar_mediaid']:'';
			
			}elseif('multi' === $action){
				$result = $app->user->getDetailedDepartmentUsers(1,true);
			}elseif('delete' === $action){
				$result = $app->user->delete($data['userid']);
			}
			//返回
			if($result['errcode'] !== 0) return $this->error(GetErrorLang($result['errcode']),$result);
			return $this->success('成功',$result);
			
		}
		return  $this->error(GetErrorLang('-1'));
		
    }

    public function MailList()
    {
        $config = $this->getConfig($this->getDefault('User'));
        $app = Factory::work($config);
        $app->server->push(function ($message) {
            switch ($message['MsgType']) {
                case 'event':
                    $this->SwitchEvent($message);
                    return '';//收到事件消息
                    break;
                default:
                    return '';//收到其它消息
                    break;
            }
        });
        $response = $app->server->serve();
        $response->send();exit;
    }
    /**
     * 运动轨迹   企业微信登录
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function Trajectory()
    {
        if($code = $this->request->request('code'))
        {
            $config = $this->getConfig($this->getDefault('Trajectory'));
            $app = Factory::work($config);
            $accessToken = $app->access_token;
            $token = $accessToken->getToken(true);
        }else{
            return $this->error(GetErrorLang('60125'),null,60125);
        }
        $data = \fast\Http::get("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}");
        $data = json_decode($data,true);
        $userData = $this->UserWork($data['UserId']);
        $tmallUser = \fast\Http::get("http://tmall.fc62.com/api/api.php?mobile={$userData['mobile']}");
        $tmallUser = json_decode($tmallUser,true);
        if($tmallUser['user_id'] == 0)
        {
            return  $this->error($tmallUser['msg']);
        }
        $userData['tmall_user'] = $tmallUser;
        return $this->success('成功',$userData);
    }

    /**
     * 获取用户信息
     * @param $UserId
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    public function UserWork($UserId)
    {
        $config = $this->getConfig($this->getDefault('User'));
        $app = Factory::work($config);
        return $app->user->get($UserId);
    }

    public function SwitchEvent($message = null)
    {
        switch ($message['ChangeType'])
        {
            case 'create_user'://创建用户
                Admin::createUser($message);
                break;
            case 'update_user'://修改用户信息
                Admin::updateUser($message['UserID'],$message);
                break;
            case 'delete_user'://删除用户
                Admin::deleteUser($message['UserID']);
                break;
            case 'create_party'://创建部门
                AuthDepartment::create(['id'=>$message['Id'],'parentid'=>$message['ParentId'],'order'=>$message['Order'],'name'=>$message['Name']]);
                break;
            case 'update_party'://更新部门
                AuthDepartment::update(['name'=>$message['Name']],['id'=>$message['Id']]);
                break;
            case 'delete_party'://删除部门
                AuthDepartment::where('id',$message['Id'])->delete();
                break;
            case 'update_tag'://标签成员变更事件
                if(isset($message['AddUserItems']))
                {
                    Admin::updateUser($message['AddUserItems'],$message);
                }
                break;
        }
    }


}
